<?php
namespace App\Models\Scope;

use Illuminate\Database\Eloquent\Scope;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Builder;


/**
 * 公司限制
 * @author litc
 */
class RoleScope implements Scope {
    
    
    public function apply(Builder $builder, Model $model)
    {
        $table = $model->getTable();
        $user = auth()->user();
        if(!$user) {
            return null;
        }

        $cid = $user->Co_ID;
        if($cid){
            $builder -> where($table.'.'.$model->getCompanyField(), '=', $cid);
        }
        
        $sid = $user->scope;
        if($sid) {
            $builder -> where($table.'.'.$model->getSiteField(), '=', $sid);
        }
        return $builder;
    }
}
